const express = require('express') //1.引入express
const router = express.Router() //2.引入路由
const { db, genid } = require('../db/DbUtils') //引入雪花id和数据库
// 添加，修改，删除，列表接口
// 列表接口
router.get('/list', async (req, res) => {
  const search_sql = 'SELECT * FROM `category` '
  let { err, rows } = await db.async.all(search_sql, [])
  if (err == null) {
    res.send({
      code: 200,
      msg: '查询成功',
      rows, //等于rows:rows
    })
  } else {
    res.send({
      code: 500,
      msg: '查询失败',
    })
  }
})
// 添加接口
router.post('/_token/add', async (req, res) => {
  //async允许异步执行
  let { name } = req.body
  const insert_sql = 'INSERT INTO `category` (`id`,`name`) VALUES(?,?)'
  // genid.NextId()是雪花id里面自动生成的id
  let { err, rows } = await db.async.run(insert_sql, [genid.NextId(), name])
  if (err == null) {
    res.send({
      code: 200,
      msg: '添加成功',
    })
  } else {
    res.send({
      code: 500,
      msg: '添加失败',
    })
  }
})
// 修改接口
router.post('/_token/update', async (req, res) => {
  // token的验证
  let { token } = req.headers
  let admin_token_sql = 'SELECT * FROM `admin` WHERE `token`=?'
  let adminResult = await db.async.all(admin_token_sql, [token])
  if (adminResult.err != null || adminResult.rows.length == 0) {
    res.send({
      code: 403,
      msg: '请先登录',
    })
    return
  }

  //async允许异步执行
  let { id, name } = req.body
  const update_sql = 'UPDATE `category` SET `name` = ? where `id` = ?'
  // genid.NextId()是雪花id里面自动生成的id
  // id是不会变的，所以要传名字
  // update_sql是传的sql语句，[]里面是要传的参数，顺序不能错
  let { err, rows } = await db.async.run(update_sql, [name, id])
  if (err == null) {
    res.send({
      code: 200,
      msg: '修改成功',
    })
  } else {
    res.send({
      code: 500,
      msg: '修改失败',
    })
  }
})

// 删除接口  /category/delete?id=xxx
router.delete('/_token/delete', async (req, res) => {
  //async允许异步执行
  let id = req.query.id
  const delete_sql = 'DELETE FROM `category` WHERE `id` =?'
  // genid.NextId()是雪花id里面自动生成的id
  // id是不会变的，所以要传名字
  // update_sql是传的sql语句，[]里面是要传的参数，顺序不能错
  let { err, rows } = await db.async.run(delete_sql, [id])
  if (err == null) {
    res.send({
      code: 200,
      msg: '删除成功',
    })
  } else {
    res.send({
      code: 500,
      msg: '删除失败',
    })
  }
})
//增加验证,后端创建token,前端每次请求都带token,token一样,才给执行
// 每一次登录都会自动生成新的token
module.exports = router //3.导出路由
